<?php

class dynamicModel extends Model {
	const TYPE_ARTICLE = 1;
	const TYPE_VIDEO = 2;

	const BIND_TYPE_DEFAULT = 0;
	const BIND_TYPE_GOODS = 1;
	const BIND_TYPE_SHOP = 2;

	const USER_TYPE_USER = 1;
	const USER_TYPE_SHOP = 2;
	const USER_TYPE_VIRTUAL = 3;

	public function validata($data) {
		$result = Validation::rule(
			array(Validation::isMust($data['content']), '内容不能为空')
		);
		return $result;
	}

	public function getList($where, $value, $order, $page, $pageSize) {
		$limit = ($page - 1) * $pageSize;
		$resultData = [
			'page' => $page,
			'pageSize' => $pageSize,
			'list' => [],
		];
		if (!$list = $this->order($order)->limit($limit, $pageSize)->getAll($where, $value)) {
			return $resultData;
		}
		$resultData['list'] = $this->buildDynamicList($list);
		return $resultData;
	}

	private function buildDynamicList($list) {
		if (!$list) {
			return [];
		}
		$result = $uids = $userData = [];
		foreach ($list as $row) {
			$uids[] = $row['uid'];
		}
		$uids = implode(',', $uids);
		if (!$userInfoList = self::model('user')->query("select uid,nickname,avatar from wf_user where uid in ({$uids})")->fetchAll()) {
			return $result;
		}
		foreach ($userInfoList as $userInfo) {
			$userData[$userInfo['uid']] = $userInfo;
		}
		unset($userInfoList);
		foreach ($list as $info) {
			// if (isset($userData[$info['uid']])) {
			// 	$result[] = [
			// 		'dynamicId' => intval($info['dynamic_id']),
			// 		'title' => strval($info['title']),
			// 		'categoryId' => intval($info['category_id']),
			// 		'image' => strval(ossModel::buildImageStyel($info['type'], $info['image'])),
			// 		'gifImage' => strval($info['gif_image']),
			// 		'type' => intval($info['type']),
			// 		'collectTotal' => intval($info['collect_total']),
			// 		'upTotal' => intval($info['up_total']),
			// 		'shareTotal' => intval($info['share_total']),
			// 		'add_time' => date('Y-m-d', strtotime($info['add_time'])),
			// 		'tag' => $info['tag'],
			// 		'tagId' => intval($info['tag_id']),
			// 		'status' => intval($info['status']),
			// 		'userInfo' => [
			// 			'uid' => intval($info['uid']),
			// 			'nickname' => strval($userData[$info['uid']]['nickname']),
			// 			'avatar' => strval($userData[$info['uid']]['avatar']),
			// 		],
			// 	];
			// }
			$nickname = '';
			$avatar = '';
			if (isset($userData[$info['uid']])) {
				$nickname = strval($userData[$info['uid']]['nickname']);
				$avatar = strval($userData[$info['uid']]['avatar']);
			}
			$result[] = [
				'dynamicId' => intval($info['dynamic_id']),
				'title' => strval($info['title']),
				'categoryId' => intval($info['category_id']),
				'image' => strval(ossModel::buildImageStyel($info['type'], $info['image'])),
				'gifImage' => strval($info['gif_image']),
				'type' => intval($info['type']),
				'collectTotal' => intval($info['collect_total']),
				'upTotal' => intval($info['up_total']),
				'shareTotal' => intval($info['share_total']),
				'add_time' => date('Y-m-d', strtotime($info['add_time'])),
				'tag' => $info['tag'],
				'tagId' => intval($info['tag_id']),
				'status' => intval($info['status']),
				'userInfo' => [
					'uid' => intval($info['uid']),
					'nickname' => $nickname,
					'avatar' => $avatar,
				],
			];

		}
		return $result;
	}

	public function getRelateDynamicList($dynamicId, $categoryId, $num) {
		$resultData = [];
		$searchNum = $num * 2;
		$sql = "SELECT * FROM `wf_dynamic` AS t1 JOIN "
			. " (SELECT dynamic_id,(rand()*timestamp(now())) as tid FROM `wf_dynamic`"
			. " WHERE category_id={$categoryId} and dynamic_id<>{$dynamicId} ) AS t2 "
			. " WHERE t1.dynamic_id = t2.dynamic_id ORDER BY t2.tid LIMIT {$num}";
		$list = $this->query($sql)->fetchAll();
		if (count($list) >= $num) {
			return $this->buildDynamicList(array_slice($list, 0, $num));
		}
		$ids = [];
		$ids[] = $dynamicId;
		if ($list) {
			foreach ($list as $info) {
				$ids[] = $info['dynamic_id'];
			}
		}
		$ids = implode(',', $ids);
		$leftNum = $searchNum - count($list);
		$sql = "SELECT * FROM `wf_dynamic` AS t1 JOIN "
			. "(SELECT dynamic_id,(rand()*timestamp(now())) as tid FROM `wf_dynamic`"
			. " WHERE dynamic_id not in ({$ids}) ) AS t2 "
			. "WHERE t1.dynamic_id = t2.dynamic_id ORDER BY t2.tid LIMIT {$leftNum}";
		$leftList = $this->query($sql)->fetchAll();
		$list = array_merge($list, $leftList);
		return $this->buildDynamicList(array_slice($list, 0, $num));
	}

	public function getListWithRelate($where, $value, $lastDynamicId, $pageSize) {
		$resultData = [
			'lastDynamicId' => 0,
			'pageSize' => $pageSize,
			'list' => [],
		];
		$where = implode(' AND ', $where);
		$sql = "select d.* from wf_dynamic d left join wf_user_relate r on"
			. " r.to_uid=d.uid where {$where} "
			. " order by d.dynamic_id desc limit {$pageSize}";
		if (!$list = $this->query($sql, $value)->fetchAll()) {
			return $resultData;
		}
		$resultData['list'] = $this->buildDynamicList($list);
		return $resultData;
	}

	public function buildInfo($info) {
		$userInfo = self::model('user')->findById($info['uid']);
		$tongji = self::model('tongji')->getOne('dates=?', date('Y-m-d', time()));
		if ($tongji) {
			if ($info['user_type'] == 1) {
				$data['majiview'] = $tongji['majiview'] + 1;
			} else {
				$data['dakaview'] = $tongji['dakaview'] + 1;
			}
			self::model('tongji')->update($data, 'id=?', $tongji['id']);
		} else {
			if ($info['user_type'] == 1) {
				$data['majiview'] = 1;
			} else {
				$data['dakaview'] = 1;
			}
			$data['dates'] = date('Y-m-d', time());
			self::model('tongji')->insert($data);
		}

		return [
			'dynamicId' => intval($info['dynamic_id']),
			'type' => intval($info['type']),
			'user_type' => intval($info['user_type']),
			'categoryId' => intval($info['category_id']),
			'title' => strval($info['title']),
			'image' => strval(ossModel::buildImageStyel($info['type'], $info['image'])),
			'imageList' => $this->buildImageList($info['image_list']),
			'gifImage' => strval($info['gif_image']),
			'type' => intval($info['type']),
			'videoUrl' => strval($info['video_url']),
			'upTotal' => intval($info['up_total']),
			'collectTotal' => intval($info['collect_total']),
			'viewTotal' => intval($info['view_total']),
			'commentTotal' => intval($info['comment_total']),
			'shareTotal' => intval($info['share_total']),
			'content' => Html::decode(strval($info['content'])),
			'addTime' => $info['add_time'],
			'bindType' => intval($info['bind_type']),
			'tag' => strval($info['tag']),
			'tagId' => intval($info['tag_id']),
			'status' => intval($info['status']),
			'bindId' => strval($info['bind_id']),
			'bindInfo' => $this->buildBindInfo($info['bind_type'], $info['bind_id']),
			'userInfo' => [
				'uid' => intval($info['uid']),
				'nickname' => strval($userInfo['nickname']),
				'avatar' => strval($userInfo['avatar']),
			],
		];
	}

	private function buildImageList($imageList) {
		if (!$imageList) {
			return [];
		}
		$imageList = explode('$$$', $imageList);
		$result = [];
		foreach ($imageList as $image) {
			$result[] = ossModel::buildImageStyel(self::TYPE_ARTICLE, $image);
		}
		return $result;
	}

	public function buildBindInfo($bindType, $bindId) {
		$result = [];
		if ($bindType == self::BIND_TYPE_DEFAULT || !$bindId) {
			return $result;
		} elseif ($bindType == self::BIND_TYPE_GOODS) {
			if (!$goodsInfoList = self::model('goods')->query("select  g.goods_id,g.name,g.image,s.sales_price,s.sale_total from wf_goods g ,wf_goods_specification s where g .goods_id =s .goods_id and s.type=2 and g .goods_id in ({$bindId})")->fetchAll()) {
				return $result;
			}
			foreach ($goodsInfoList as $goodsInfo) {
				$result[] = [
					'id' => intval($goodsInfo['goods_id']),
					'name' => $goodsInfo['name'],
					'image' => $goodsInfo['image'],
					'price' => floatval($goodsInfo['sales_price']),
					'saleTotal' => intval($goodsInfo['sale_total']),
				];
			}
		} elseif ($bindType == self::BIND_TYPE_SHOP) {
			if (!$shopInfo = self::model('shop')->getOne('shop_id=?', $bindId)) {
				return $result;
			}
			$result[] = [
				'id' => intval($shopInfo['shop_id']),
				'name' => $shopInfo['name'],
				'image' => $shopInfo['image'],
				'price' => 0,
			];
		}
		return $result;
	}
}